package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.exception.BusinessException;
import com.microtf.inscription.framework.pojo.wechat.resource.Token;
import com.microtf.inscription.jpa.entity.MiniApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Optional;

/**
 * 微信
 *
 * @author guliuzhong
 */
@Service
public class WeChatServiceBase {
    /**
     * 应用程序配置
     */
    MiniAppService miniAppService;

    @Autowired
    public void setMiniAppService(MiniAppService miniAppService) {
        this.miniAppService = miniAppService;
    }
    RedisTemplate<String, Token> tokenRedisTemplate;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        this.tokenRedisTemplate =  (RedisTemplate<String, Token>)redisTemplate;
    }
    NetService netService;

    @Autowired
    public void setNetService(NetService netService) {
        this.netService = netService;
    }


    /**
     * 微信程序配置
     */
    ThreadLocal<MiniApp> miniAppThreadLocal = new ThreadLocal<>();

    public void init(Integer appId) {
        Optional<MiniApp> miniApp = miniAppService.getMiniApp(appId);
        miniApp.ifPresent(item -> miniAppThreadLocal.set(item));
    }

    public void release() {
        miniAppThreadLocal.remove();
    }
    public Token getToken() {
        MiniApp miniApp = miniAppThreadLocal.get();
        Token tokenRedis = tokenRedisTemplate.opsForValue().get("wechat.toke" + miniApp.getId());
        int tokenExpire = 7100000;
        if (tokenRedis != null && tokenRedis.getCreateDate().after(new Date(System.currentTimeMillis() - tokenExpire))) {
            return tokenRedis;
        }
        HashMap<String, String> getMap = new HashMap<>(2);
        getMap.put("appid", miniApp.getAppId());
        getMap.put("secret", miniApp.getAppSecret());
        String apiToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        Token token = netService.newRequest().setUrl(apiToken, getMap).requestToObject(Token.class);
        if (token.getErrorResponse() != null && token.getErrorResponse().getCode() != null) {
            throw new BusinessException("微信token获取失败原因：" + token.getErrorResponse().getMsg());
        }
        token.setAppId(miniApp.getId());
        token.setCreateDate(new Date());
        tokenRedisTemplate.opsForValue().set("wechat.toke" + miniApp.getId(), token);
        return token;
    }
}